//
//  RZMessageCell.m
//  RZIM
//
//  Created by reyzhang on 2021/8/19.
//

#import "RZMessageCell.h"
#import "RZKitUtility.h"
#import "RZKitCommonDefine.h"
#import "RZMessageCellTool.h"
#import <SDWebImage/SDWebImage.h>
#import "RZIMConfig.h"
#import "RZIMDefine.h"


// 头像
#define PortraitImageViewTop 0
// 气泡
#define ContentViewBottom 14
#define DefaultMessageContentViewWidth 200
#define StatusContentViewWidth 100
#define DestructBtnWidth 20
#define StatusViewAndContentViewSpace 8

@interface RZMessageCell ()

@property (nonatomic, assign) BOOL showBubbleBackgroundView;
@end



@implementation RZMessageCell
#pragma mark - Life Cycle

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self rcinit];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self rcinit];
    }
    return self;
}

- (void)rcinit{
    [self setupMessageCellView];
    [self registerMessageCellNotification];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Super Methods

- (void)setDataModel:(RZMessageInfo *)model {
    [super setDataModel:model];
    
    //泡泡的背景图
    if (self.showBubbleBackgroundView) {
        self.bubbleBackgroundView.image = [RZMessageCellTool getDefaultMessageCellBackgroundImage:self.model];
    }
    
    //头像
    [self.portraitImageView sd_setImageWithURL:[NSURL URLWithString:model.userAvatar] placeholderImage:nil options:SDWebImageRetryFailed];
    
    //昵称
    self.nicknameLabel.text = model.username;

    
    //重新布局头像及昵称的显示位置
    [self setCellAutoLayout];
}

#pragma mark - Public Methods


- (void)showBubbleBackgroundView:(BOOL)show{
    self.showBubbleBackgroundView = show;
    self.bubbleBackgroundView.userInteractionEnabled = show;
    if (show){
        [self.messageContentView sendSubviewToBack:self.bubbleBackgroundView];
    }else{
        self.bubbleBackgroundView = nil;
    }
}


#pragma mark - Private Methods

- (void)setupMessageCellView {
//    self.delegate = nil;

    [self.baseContentView addSubview:self.portraitImageView];
    [self.baseContentView addSubview:self.nicknameLabel];
    [self.baseContentView addSubview:self.messageContentView];

    [self setPortraitStyle:RZIMConfigCenter.ui.globalMessageAvatarStyle];
}

- (void)registerMessageCellNotification{
    
    [self registerUpdateLayoutIfNeed];
    
}

- (void)registerUpdateLayoutIfNeed{
    __weak typeof(self) weakSelf = self;
    
    [self.messageContentView registerSizeChangedEvent:^(CGSize size) {
        if (weakSelf.model){
            CGRect rect = CGRectMake(0, 0, size.width, size.height);
            
            if(weakSelf.model.messageDirection == MessageDirection_RECEIVE) {
                rect.origin.x = PortraitViewEdgeSpace + RZIMConfigCenter.ui.globalMessagePortraitSize.width + HeadAndContentSpacing;
                CGFloat messageContentViewY = PortraitImageViewTop;
                if (weakSelf.model.isDisplayNickname) {
                    messageContentViewY = PortraitImageViewTop + NameHeight + NameAndContentSpace;
                }
                rect.origin.y = messageContentViewY;
            } else {
                rect.origin.x = weakSelf.baseContentView.bounds.size.width - (size.width + HeadAndContentSpacing + RZIMConfigCenter.ui.globalMessagePortraitSize.width + PortraitViewEdgeSpace);
                rect.origin.y = PortraitImageViewTop;
            }
            
            weakSelf.messageContentView.frame = rect;
        }
        if (weakSelf.showBubbleBackgroundView) {
            weakSelf.bubbleBackgroundView.frame = weakSelf.messageContentView.bounds;
        }
    }];
}

- (void)setPortraitStyle:(RZUserAvatarStyle)portraitStyle {
    _portraitStyle = portraitStyle;
    if (_portraitStyle == USER_AVATAR_RECTANGLE) {
        self.portraitImageView.layer.cornerRadius = RZIMConfigCenter.ui.portraitImageViewCornerRadius;
    }
    if (_portraitStyle == USER_AVATAR_CYCLE) {
        self.portraitImageView.layer.cornerRadius = [RZIMConfigCenter.ui globalMessagePortraitSize].height / 2;
    }
    self.portraitImageView.layer.masksToBounds = YES;
}

- (void)setCellAutoLayout {
    // receiver 左侧显示
    if (MessageDirection_RECEIVE == self.model.messageDirection) {
        self.nicknameLabel.hidden = !self.model.isDisplayNickname;
        CGFloat portraitImageX = PortraitViewEdgeSpace;
        self.portraitImageView.frame =
        CGRectMake(portraitImageX, PortraitImageViewTop, RZIMConfigCenter.ui.globalMessagePortraitSize.width,
                   RZIMConfigCenter.ui.globalMessagePortraitSize.height);
        self.nicknameLabel.frame =
        CGRectMake(portraitImageX + self.portraitImageView.bounds.size.width + HeadAndContentSpacing, PortraitImageViewTop, DefaultMessageContentViewWidth, NameHeight);
    } else { // owner 自己的发送的消息 右侧显示
        self.nicknameLabel.hidden = YES;
        CGFloat portraitImageX =
        self.baseContentView.bounds.size.width - (RZIMConfigCenter.ui.globalMessagePortraitSize.width + PortraitViewEdgeSpace);
        self.portraitImageView.frame =
        CGRectMake(portraitImageX, PortraitImageViewTop, RZIMConfigCenter.ui.globalMessagePortraitSize.width,
                   RZIMConfigCenter.ui.globalMessagePortraitSize.height);
    }
    self.messageContentView.contentSize = CGSizeMake(DefaultMessageContentViewWidth,self.baseContentView.bounds.size.height - ContentViewBottom);
//    [self updateStatusContentView:self.model];
}



#pragma mark - Target Action

- (void)tapUserPortaitEvent:(UIGestureRecognizer *)gestureRecognizer {
    __weak typeof(self) weakSelf = self;
    if ([self.delegate respondsToSelector:@selector(didTapCellPortrait:)]) {
        [self.delegate didTapCellPortrait:weakSelf.model.uid];
    }
}

- (void)longPressUserPortaitEvent:(UIGestureRecognizer *)gestureRecognizer {
    __weak typeof(self) weakSelf = self;
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        if ([self.delegate respondsToSelector:@selector(didLongPressCellPortrait:)]) {
            [self.delegate didLongPressCellPortrait:weakSelf.model.uid];
        }
    }
}

- (void)longPressedMessageContentView:(id)sender {
    UILongPressGestureRecognizer *press = (UILongPressGestureRecognizer *)sender;
    if (press.state == UIGestureRecognizerStateEnded) {
        return;
    } else if (press.state == UIGestureRecognizerStateBegan) {
        [self.delegate didLongTouchMessageCell:self.model inView:self.messageContentView];
    }
}

- (void)didTapMessageContentView{
    NSLog(@"%s", __FUNCTION__);
    if ([self.delegate respondsToSelector:@selector(didTapMessageCell:)]) {
        [self.delegate didTapMessageCell:self.model];
    }
}

#pragma mark - Getter && Setter

- (UIImageView *)portraitImageView{
    if (!_portraitImageView) {
        _portraitImageView = [[UIImageView alloc] initWithImage:RZResourceImage(@"default_portrait_msg")];
        //点击头像
        UITapGestureRecognizer *portraitTap =
            [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapUserPortaitEvent:)];
        portraitTap.numberOfTapsRequired = 1;
        portraitTap.numberOfTouchesRequired = 1;
        [_portraitImageView addGestureRecognizer:portraitTap];

        UILongPressGestureRecognizer *portraitLongPress =
            [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressUserPortaitEvent:)];
        [_portraitImageView addGestureRecognizer:portraitLongPress];

        _portraitImageView.userInteractionEnabled = YES;
    }
    return _portraitImageView;
}

- (UILabel *)nicknameLabel{
    if (!_nicknameLabel) {
        _nicknameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _nicknameLabel.backgroundColor = [UIColor clearColor];
        [_nicknameLabel setFont:[RZIMConfigCenter.font fontOfAnnotationLevel]];
        [_nicknameLabel
            setTextColor:[UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1]];
    }
    return _nicknameLabel;
}


- (RZContentView *)messageContentView{
    if (!_messageContentView) {
        _messageContentView = [[RZContentView alloc] init];
        UILongPressGestureRecognizer *longPress =
        [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressedMessageContentView:)];
        [_messageContentView addGestureRecognizer:longPress];

        UITapGestureRecognizer *tap =
            [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapMessageContentView)];
        tap.numberOfTapsRequired = 1;
        tap.numberOfTouchesRequired = 1;
        [_messageContentView addGestureRecognizer:tap];
        _messageContentView.userInteractionEnabled = YES;
    }
    return _messageContentView;
}

- (UIImageView *)bubbleBackgroundView{
    if (!_bubbleBackgroundView) {
        _bubbleBackgroundView = [[UIImageView alloc] initWithFrame:CGRectZero];
        [self.messageContentView addSubview:self.bubbleBackgroundView];
    }
    return _bubbleBackgroundView;
}
@end
